menuList[5].onclick();

// 获取数据并渲染
current=1;
pageSize=10;
let searchContent = -1;
let flagData=1;//判断当前分页数据是那些类型 1、所有数据 2、搜索结果 
async function fun(flagOptions){
    let checkAll = document.querySelector("#checkAll");
    checkAll.checked = false;
    dels=[];
    if(flagData==1){
        result = await getData(current,pageSize);
        counts = result.data.totalCounts;
        console.log(counts);
        pages = result.data.totalPage;
        pageFun({
            current:current,
            pages:pages,
            counts:counts,
            flagOptions:flagOptions,
            pageSize:pageSize
        })
    }else if(flagData==2){
        searchByUsername();
    }else if(flagData==3){
        result = await getStateFun(current,pageSize);
        counts = result.data.totalCounts;
        console.log(counts);
        pages = result.data.totalPage;
        pageFun({
            current:current,
            pages:pages,
            counts:counts,
            flagOptions:flagOptions,
            pageSize:pageSize
        })
    }else if(flagData==4){
        result = await getStateRealFun(current,pageSize);
        counts = result.data.totalCounts;
        console.log(counts);
        pages = result.data.totalPage;
        pageFun({
            current:current,
            pages:pages,
            counts:counts,
            flagOptions:flagOptions,
            pageSize:pageSize
        })
    }
}
fun(0);
function getData(current,pageSize){
    return new Promise((resolve, reject) => {
        axios({
            url:'/admin/users/ManagerUsers',
            method:'GET',
            params:{
                page:current,
                size:pageSize
                }
            })
            .then(data => {
                decorateFun(data)
                console.log(data.data);
                resolve(data.data);
            })
            .catch(err => {
                console.log(err);
            })
    });
   
}

// 选择出生年月日
var selYear = window.document.getElementById("selYear");
var selMonth = window.document.getElementById("selMonth");
var selDay = window.document.getElementById("selDay");
// 新建一个DateSelector类的实例，将三个select对象传进去
//  let birth = 
new DateSelector(selYear, selMonth, selDay);
function birthFun(year, month, day) {
    let optionsY = selYear.querySelectorAll("option");
    let optionsM = selMonth.querySelectorAll("option");
    let optionsD = selDay.querySelectorAll("option");
    let i=0;
    for(let key of optionsY){
        if(key.getAttribute('value')==year){
            optionsY[i].setAttribute("selected", "selected");
        }
        i++
    }
    i=0;
    for(let key of optionsM){
        if(key.getAttribute('value')==month){
            optionsM[i].setAttribute('selected', 'selected')
        }
        i++
    }
    i=0
    for(let key of optionsD){
        if(key.getAttribute('value')==day){
            optionsD[i].setAttribute('selected', 'selected')
        }
        i++
    }
}

// 失去焦点判断
function userOnblurFun(e){
    e=e || window.event;
    var target=e.target || e.srcElement;
    let name = target.getAttribute("name");
    console.log(name);
    if(name == "email"){
        if(!isEmail(target.value)){
            // explain({
            //     code:3,
            //     msg:"请见检查邮箱是否正确",
            //     time:3000
            // })
            return false;  
        }
    }else if(name=="telephone"){
        if(!isTelCode(target.value)){
            explain({
                code:3,
                msg:"请见检查邮箱是否正确",
                time:3000
            })
            return false;  
        }
    }

}

// 添加用户表单
function openAddUserFun(){
    console.log("aa");
    let addUserWindow = cl("addUserWindow");
    let covers = document.getElementsByClassName("covers")[0];
    let addUserTitle = document.getElementsByClassName("addUserTitle")[0];
    let addUserFrom = document.getElementsByClassName("addUserFrom")[0];
    let submitBtn = document.getElementsByClassName("submitBtn")[0];
    submitBtn.setAttribute("onclick","submitAddUserFun()")
    addUserFrom.reset();
    addUserTitle.innerHTML = "添加用户"
    covers.style.display = "block";
    addUserWindow.style.display = "block";
}
// 提交添加用户表单
function submitAddUserFun (){
    let addUserFrom = cl("addUserFrom");
    let formMsg = serialize(addUserFrom);
    console.log(formMsg);
    console.warn(email.value);
    if(formMsg.email.length==0||formMsg.password.length==0||formMsg.sex.length==0||formMsg.telephone.length==0||formMsg.nickname.length==0){
        explain({
            code:3,
            msg:"请见检查信息是否填写完整",
            time:3000
        })
    }else{
        axios({
            url:'/admin/users/addAUser',
            method:'POST',
            params:{
                email: email.value,
                password:formMsg.password[0],
                birth:selYear.value+"-"+ selMonth.value + "-" + selDay.value ,
                sex:formMsg.sex[0]==0?"男":"女",
                telephone:formMsg.telephone[0],
                nickname:formMsg.nickname[0],
                flag:0,
                }
            })
            .then(data => {
                console.log(data);
                if(data.data.code==20000){
                    closeUSerFun();
                    fun(0);
                    explain({
                        code:1,
                        msg:"添加成功",
                        time:3000
                    })
                }else{
                    explain({
                        code:2,
                        msg:data.data.data,
                        time:3000
                    })
                }
            })
            .catch(err => {
                console.log(err);
            })
    }
}

// 批量删除
function openDeleteUsersFun(){
    console.log(dels);
    if(dels.length==0){
        explain({
            code:3,
            msg:"请选择需要删除的用户",
            time:3000
        })
    }else{
        pointFun({
            code:1,
            msg:"是否确认删除选中的用户"
        })
    }
}
function deleteUsersFun(){
    axios({
        url:'/admin/users/deleteUsers',
        method:'DELETE',
        params:{
            ids:dels
        }
    })
    .then(data => {
        console.log(data);
        if(data.data.code==20000){
            closeUSerFun();
            fun(0);
            explain({
                code:1,
                msg:"删除成功",
                time:3000
            })
        }
    })
    .catch(err => {
        console.log(err);
    })
}
// 删除单个用户
let userid;
function openDeleteUserFun(e){
    e=e || window.event;
    var target=e.target || e.srcElement;
    userid=target.getAttribute('name');
    pointFun({
        code:2,
        msg:"是否删除该用户"
    })
    console.warn(target.getAttribute('name'));
}
function deleteUserFun(){
    axios({
        url:'/admin/users/deleteAUser',
        method:'DELETE',
        params:{
            userId:userid
        }
    })
    .then(data => {
        console.log(data);
        if(data.data.code==20000){
            closeUSerFun();
            fun(0);
            explain({
                code:1,
                msg:"删除成功",
                time:3000
            })
        }
    })
    .catch(err => {
        console.log(err);
    })
}
// 搜索通过用户名
let searchInput = cl("searchInput");
function searchByUsername(){
    if(searchContent != searchInput.value){
        page=1;
        pageSize=10;
        current=1;
    } 
    console.warn(searchContent==searchInput.value);
    axios({
        url: '/admin/users/selectUsers',
        method: 'GET',
        params:{
            nickname : searchInput.value,
            page: current,
            size: pageSize
            }
        })
        .then(data => {
            if(data.data.code==20001){
                explain({
                    code:2,
                    msg:"抱歉未找到",
                    time:3000
                })
            }else{
                searchContent = searchInput.value
                flagData=2;
                result = data.data.data;
                counts = result.totalCounts;
                pages = result.totalPage
                console.log(result);
                decorateFun(data)
                pageFun({
                    current:current,
                    pages:result.totalPage,
                    counts:result.totalCounts,
                    pageSize:result.size
                })
            }
        })
        .catch(err => {
            console.log(err);
        })
}

// 渲染页面
function decorateFun(data){
    let tbodyMenu = cl("tbodyMenu");
    let dataNums = cl("dataNums");
    let pageMessage = cl("pageMessage");
    let end;
    if(current==1){
        console.log(data);
        end=data.data.data.users.length;
    }else{
        end =parseInt(current-1)*parseInt(data.data.data.size)+parseInt(data.data.data.users.length);
    }
    dataNums.innerHTML = data.data.data.users.length;
    pageMessage.innerHTML = `第${(current-1)*data.data.data.size+1}到${end}条记录，共${data.data.data.totalCounts}条`;
    tbodyMenu.innerHTML ="";
    let i=0;
    for(let key of data.data.data.users){
        tbodyMenu.innerHTML += `
        <tr>
            <td><input type="checkbox" class="checkbox" name="${key.userId}" onclick="checkboxFun()" target="${i}"  ></td>
            <td class="userName" name="${key.userId}" onclick="checkUserInfo()">${key.nickname==null ? "(未设置)" : key.nickname}</td>
            <td><img class="headimgSmall" id="${key.userId}" src="${key.img}" onclick="openImgWin()" alt="点击放大"></td>
            <td>${key.email}</td>
            <td>${key.telephone==null ? "(未设置)": key.telephone}</td>
            <td class="realNameTd" name="${key.userId}" onclick="lookRealName()"> 查看</td>
            <td>${key.flag==0?"普通用户":"商家"}</td>
            <td>${key.birth==null?'未设置':key.birth}</td>
            <td>${key.vip==0?"非会员":"会员"}</td>
            <td>
            <button class="btn editBtn"><i name="${key.userId}" onclick="openChageUserInfoFun()" class="iconfont bianji"></i></button>
            <button class="btn delBtn"><i name="${key.userId}" onclick="openDeleteUserFun()" class="iconfont shanchu"></i></button>
            </td>
        </tr>
            `
            i++
        }
}
// 输入框回车事件

function inputEnterFun(){
    console.log("a");
    if(event.keyCode == 13){
        searchByUsername()
    }
}

// 页面刷新
function reloadFun(){
    location.reload();
}

// 选择每页展示数量
function chooseSizeFun(){
    let selectNums = document.getElementById("selectNums");
    console.log(selectNums.children[1]);
    console.warn(selectNums.value);
    current = 1;
    pageSize =selectNums.value;
    fun(1);
    for(let i=0;i<selectNums.children.length;i++) {
        if(selectNums.children.length[i]==selectNums.value){
            selectNums.children.length[i].select="select";
        }
    }
}
// 根据用户的状态进行筛选
function chooseFlagFun(){
    flagData=3;
    current = 1;
    pageSize =10;
    fun();
}
function getStateFun(){
    let selectFlag = document.getElementById("selectFlag");
    console.warn(selectFlag.value);
    if(selectFlag.value==-1){
        // location.reload()
        flagData=1;
        fun();
    }else{
        return new Promise((resolve, reject) => {
            axios({
                url:'/admin/users/findUsersByClass',
                method:'GET',
                params:{
                    page:current,
                    size:pageSize,
                    flag:selectFlag.value
                    }
                })
                .then(data => {
                    decorateFun(data)
                    console.log(data.data);
                    resolve(data.data);
                })
                .catch(err => {
                    console.log(err);
                })
        });
    }
}
// 根据用户的实名认证状态进行筛选
function chooseRealFun(){
    flagData=4;
    current = 1;
    pageSize =10;
    fun();
}
function getStateRealFun(){
    let selectRealName = document.getElementById("selectRealName");
    console.warn(selectRealName.value);
    if(selectRealName.value==-1){
        // location.reload()
        flagData=1;
        fun();
    }else{
        return new Promise((resolve, reject) => {
            axios({
                url:'/admin/users/findAllRealName',
                method:'GET',
                params:{
                    page:current,
                    size:pageSize,
                    flag:selectRealName.value
                    }
                })
                .then(data => {
                    console.log(data.data);
                    decorateFun(data)
                    resolve(data.data);
                })
                .catch(err => {
                    console.log(err);
                })
        });
    }
}
// 通过id查询用户信息
function getDataById(){
    return new Promise((resolve, reject) => {
        axios({
            url:'/admin/users/findById',
            method:'GET',
            params:{
               userId:userid
                }
            })
            .then(data => {
                if(data.data.code==20000){
                    resolve(data.data);
                }
            })
            .catch(err => {
                console.log(err);
            })
    });
}

// 编辑用户信息
async function openChageUserInfoFun(e){
    e=e || window.event;
    var target=e.target || e.srcElement;
    userid = target.getAttribute("name");
    let addUserWindow = cl("addUserWindow");
    let covers = document.getElementsByClassName("covers")[0];
    let addUserTitle = document.getElementsByClassName("addUserTitle")[0];
    let addUserFrom = document.getElementsByClassName("addUserFrom")[0];
    let submitBtn = document.getElementsByClassName("submitBtn")[0];
    let male = document.getElementById("male");
    let female = document.getElementById("female");
    let flag0 = document.getElementById("flag0");
    let flag1 = document.getElementById("flag1");
    addUserFrom.reset();
    addUserTitle.innerHTML = "编辑用户信息"
    submitBtn.setAttribute("onclick","submitChangeUserFun()")
    covers.style.display = "block";
    addUserWindow.style.display = "block";
    let userData = await getDataById();
    console.warn(userData.data.birth);
    if(userData.data.birth!=null||userData.data.birth!=undefined){
        let birthArr = userData.data.birth.split('-');
        birthFun(birthArr[0],birthArr[1],birthArr[2])
    }
    email.value=userData.data.email;
    password.value=userData.data.password;
    telephone.value=userData.data.telephone;
    nickname.value=userData.data.nickname;
    console.log(userData.data.sex=='男');
    console.log(userData.data.sex=='女');
    if(userData.data.sex=='男'){
        male.setAttribute('checked','checked')
        female.removeAttribute('checked')
    }else{
        female.setAttribute('checked','checked')
        male.removeAttribute('checked')
    }
    if(userData.data.flag==0){
        flag0.setAttribute('checked','checked')
        flag1.removeAttribute('checked')
    }else{
        flag1.setAttribute('checked','checked')
        flag0.removeAttribute('checked')
    }
}
// 查看用户信息
async function checkUserInfo(e){
    e=e || window.event;
    var target=e.target || e.srcElement;
    userid = target.getAttribute("name");
    let userData = await getDataById();
    let userInfoWindow = cl("userInfoWindow");
    let userInfoMsg = cl("userInfoMsg");
    let covers = cl("covers");
    console.log(userData);
    userInfoMsg.innerHTML="";
    userInfoMsg.innerHTML +=`
    <img src="${userData.data.img==null ? '未设置' : userData.data.img}" alt="">
    <div>
        <span>用户名：</span>
        <span>${userData.data.nickname==null?'':userData.data.nickname}</span>
    </div>
    <div>
        <span>性别：</span>
        <span>${userData.data.sex}</span>
    </div>
    <div>
        <span>电话：</span>
        <span>${userData.data.telephone==null?'未设置':userData.data.telephone}</span>
    </div>
    <div>
        <span>邮箱：</span>
        <span>${userData.data.email==null?'未设置':userData.data.email}</span>
    </div>
    <div>
        <span>出生日期：</span>
        <span>${userData.data.birth==null?'未设置':userData.data.birth}</span>
    </div>
    <div>
        <span>状态：</span>
        <span>${userData.data.flag==0?'用户':'商家'}</span>
    </div>
    <div>
        <span>是否VIP：</span>
        <span>${userData.data.vip==0?'是':'否'}</span>
    </div>
    
    `
    userInfoWindow.style.display ='block';
    covers.style.display ='block';
}
// 提交编辑用户表单
function submitChangeUserFun (){
    let addUserFrom = cl("addUserFrom");
    let formMsg = serialize(addUserFrom);
    console.log(formMsg);
    console.warn(email.value);
    if(formMsg.email.length==0||formMsg.password.length==0||formMsg.sex.length==0||formMsg.telephone.length==0||formMsg.nickname.length==0){
        explain({
            code:3,
            msg:"请见检查信息是否填写完整",
            time:3000
        })
    }else{
        axios({
            url:'/admin/users/updateAVip',
            method:'POST',
            params:{
                email: email.value,
                password:formMsg.password[0],
                birth:selYear.value+"-"+ selMonth.value + "-" + selDay.value ,
                sex:formMsg.sex[0]==0?"男":"女",
                telephone:formMsg.telephone[0],
                nickname:formMsg.nickname[0],
                flag:formMsg.flag[0],
                userId:userid
                }
            })
            .then(data => {
                console.log(data);
                if(data.data.code==20000){
                    closeUSerFun();
                    fun(0);
                    explain({
                        code:1,
                        msg:"修改成功",
                        time:3000
                    })
                }else{
                    explain({
                        code:2,
                        msg:data.data.data,
                        time:3000
                    })
                }
            })
            .catch(err => {
                console.log(err);
            })
    }
}

// 头像的操作

// 预览头像
function fileFun(){
    let headimgBig = cl("headimgBig");
    let file = cl("file");
    let imgFile = file.files[0];
    let imgSrc = window.URL.createObjectURL(imgFile);
    headimgBig.setAttribute('src', imgSrc);
}
// 展示放大图像
function openImgWin(e){
    let headimgBig = cl("headimgBig");
    let changeImgWin = cl("changeImgWin");
    let covers = document.getElementsByClassName("covers")[0];
    e=e || window.event;
    var target=e.target || e.srcElement;
    let src = target.getAttribute("src");
    userid = target.getAttribute("id");
    changeImgWin.style.display ='block'
    covers.style.display ='block'
    headimgBig.src = src;
}
// 修改头像
function submitChangeImgFun(){
    console.log(userid);
    let file = cl("file");
    
    var formData = new FormData()
    formData.append('multipartFile',file.files[0]);
    axios({
        url: `/admin/users/updateAVipImg?userId=${userid}`,
        data: formData,
        method: 'put'
    }).then((data) => {
        console.log(data)
        if(data.data.data.code==20000){
            fun();
            explain({
                code:1,
                msg:"修改成功",
                time:3000
            })
            closeUSerFun()
        }
    }).catch((err) => {
        console.log(err)
    })
}

// 关闭的操作
function closeUSerFun(){
    let userInfoWindow =cl("userInfoWindow");
    let covers = cl("covers");
    let changeImgWin = cl("changeImgWin");
    var addUserWindow = cl("addUserWindow");
    userInfoWindow.style.display = 'none';
    covers.style.display = 'none';
    changeImgWin.style.display = 'none';
    addUserWindow.style.display = 'none';
}
// 查看实名信息
function lookRealName(e){
    e=e || window.event;
    var target=e.target || e.srcElement;
    userid = target.getAttribute("name");
    axios({
        url: `/admin/users/findRealNameA`,
        method: 'GET',
        params: {
            userId: userid
        }
    })
    .then(data => {
      console.log(data.data);
      if(data.data.code==20000){
          location.href = `/admin/users/findRealName?userId=${userid}&`;
      }else{
        // location.href='/admin/error'
          explain({
              code:3,
              msg:data.data.data,
              time:3000
          })
      }
    })
    .catch(err => {
        
       explain({
        code:3,
        msg:"该用户还未进行实名认证"
        })
       
    })
}